<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
import { reqUploadEmployees } from '@/api/employees'
export default {
  name: 'Import',
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  methods: {
    async handleSuccess({ results, header }) {
      // console.log(results, header)
      // 页面渲染需要的是对象数组
      if (this.type === 'user') {
        const arr = []
        const userRelations = {
          '入职日期': 'timeOfEntry',
          '手机号': 'mobile',
          '姓名': 'username',
          '转正日期': 'correctionTime',
          '工号': 'workNumber'
        }
        results.forEach(item => {
          // console.log(item)
          const obj = {}
          for (const key in item) {
            // console.log(item[key], key)
            const englishKey = userRelations[key]
            // console.log(englishKey)
            obj[englishKey] = item[key]
            // console.log(obj)
          }
          arr.push(obj)
        })
        let test = []
        let test2 = []
        test = arr.map(item => this.formatExcelDate(item.timeOfEntry))
        test2 = arr.map(item => this.formatExcelDate(item.correctionTime))
        arr.forEach((item, index) => {
          item.timeOfEntry = test[index]
          item.correctionTime = test2[index]
        })
        await reqUploadEmployees(arr)
        console.log(arr)
        this.$router.back()
      }
    },
    formatExcelDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
